package com.movie.config;

import com.movie.util.JwtUtil;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class JwtRequestFilter extends OncePerRequestFilter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        final String authorizationHeader = request.getHeader("Authorization");
        System.out.println("[JwtFilter] Request URI: " + request.getRequestURI()); // Log URI
        System.out.println("[JwtFilter] Authorization Header: " + authorizationHeader);

        String username = null;
        String jwt = null;

        // 检查 Header 是否存在且以 "Bearer " 开头
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            jwt = authorizationHeader.substring(7);
            System.out.println("[JwtFilter] Extracted JWT: " + jwt);
            try {
                username = jwtUtil.extractUsername(jwt);
                System.out.println("[JwtFilter] Username extracted from JWT: " + username);
            } catch (IllegalArgumentException e) {
                System.out.println("[JwtFilter] Unable to get JWT Token: " + e.getMessage());
            } catch (ExpiredJwtException e) {
                System.out.println("[JwtFilter] JWT Token has expired: " + e.getMessage());
            }
        } else {
            System.out.println("[JwtFilter] Authorization header does not start with Bearer String");
        }

        // 如果获取到用户名且当前 SecurityContext 中没有认证信息
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            System.out.println("[JwtFilter] SecurityContext is null, attempting to authenticate user: " + username);
            UserDetails userDetails = null;
            try {
                 userDetails = this.userDetailsService.loadUserByUsername(username);
                 System.out.println("[JwtFilter] UserDetails loaded for username: " + username);
            } catch (Exception e) {
                 System.out.println("[JwtFilter] Error loading UserDetails: " + e.getMessage());
            }

            // 如果 token 有效且 UserDetails 加载成功
            if (userDetails != null && jwtUtil.validateToken(jwt, userDetails)) {
                System.out.println("[JwtFilter] JWT Token is valid for user: " + username);
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                usernamePasswordAuthenticationToken
                        .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                // 设置认证信息到 SecurityContext
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
                System.out.println("[JwtFilter] Authentication set in SecurityContext for user: " + username);
            } else {
                 System.out.println("[JwtFilter] JWT Token validation failed or UserDetails not loaded for user: " + username);
            }
        } else {
             System.out.println("[JwtFilter] Username is null or SecurityContext already contains Authentication.");
        }

        System.out.println("[JwtFilter] Proceeding with filter chain...");
        chain.doFilter(request, response);
    }
} 